<?php
/**
 * Gold Ajaxcart Module
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Gold
 * @package     Gold_Ajaxcart
 * @copyright   Copyright (c) 2011 Gold
 * @Author $Id: CartController.php 544 2011-09-26 03:35:19Z gold $
*/

/**
 * Shopping cart controller
 */
require_once('Mage/Checkout/controllers/CartController.php');
class Gold_Ajaxcart_CartController extends Mage_Checkout_CartController
{
    /**
     * Add product to shopping cart action
     */
    public function ajaxaddAction()
    {    	
        $cart   = $this->_getCart();
        $params = $this->getRequest()->getParams();
        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();
            $related = $this->getRequest()->getParam('related_product');

            /**
             * Check product availability
             */
            if (!$product) {
                $this->_goBack();
                return;
            }

            if (isset($params['in_cart']))
            {
            	$cart->updateItem($params['itemId'], new Varien_Object($params));
            }
            else 
            {
            	$cart->addProduct($product, $params);
            }            
            if (!empty($related)) {
                $cart->addProductsByIds(explode(',', $related));
            }

            $cart->save();

            $this->_getSession()->setCartWasUpdated(true);            
            /**
             * @todo remove wishlist observer processAddToCart
             */
            Mage::dispatchEvent('checkout_cart_add_product_complete',
                array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
            );

            if (!$this->_getSession()->getNoCartRedirect(true)) {
                if (!$cart->getQuote()->getHasError()){
                	if (isset($params['in_cart']))
                	{
                		$message = $this->__('Update successfully.');
                	}
                	else
                	{
                		$message = $this->__('%s item(s) was added to your shopping cart.', (empty($params['qty'])? 1 : intval($params['qty'])));	
                	}                    
                    $this->_getSession()->addSuccess($message);
                }
                //$this->_goBack();
            }
            return $this->getResponse()->setBody($this->_getAjaxCartHtml());
        } catch (Mage_Core_Exception $e) {
            if ($this->_getSession()->getUseNotice(true)) {
                $this->_getSession()->addNotice($e->getMessage());
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->_getSession()->addError($message);
                }
            }			
        } catch (Exception $e) {
            $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
            Mage::logException($e);
        }
        return $this->getResponse()->setBody($this->_getAjaxCartErrorHtml());
    }
    
    protected function _getAjaxCartHtml()
    {
    	$layout = $this->getLayout();
    	$update = $layout->getUpdate();
    	$update->load('ajaxcart_cart_ajaxadd');  
    	$this->_initLayoutMessages('checkout/session');
        $this->_initLayoutMessages('catalog/session');  
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();
        return $output;
    }
    
	protected function _getAjaxCartErrorHtml()
    {
    	$layout = $this->getLayout();
    	$update = $layout->getUpdate();
    	$update->load('ajaxcart_cart_error');  
    	$this->_initLayoutMessages('checkout/session');
        $this->_initLayoutMessages('catalog/session');  
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();
        return $output;
    }
    	    
    protected function _getMiniCartHtml()
    {
    	$layout = $this->getLayout();
    	$update = $layout->getUpdate();
    	$update->load('ajaxcart_minicart'); 
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();
        return $output;
    }
    
    public function ajaxupdateMiniCartAction()
    {
    	$result = $this->_getMiniCartHtml();
    	$body = 'AjaxCart.updateBlock($$("div.mini-cart"),'.Mage::helper('core')->jsonEncode($result).');';
    	$body .= 'if($$("div.cart")!=""){AjaxCart.ajaxUpdateBlock("'.Mage::getUrl('*/*/ajaxUpdateCartPage/', array('_secure'=>true)).'");';
        $body .= 'if($$("div.crosssell")!=""){AjaxCart.ajaxUpdateBlock("'.Mage::getUrl('*/*/ajaxUpdateCrossell/', array('_secure'=>true)).'");}';
        $body .='if(typeof(billing)!="undefined"){billing.update();}'; 
        $body .= '}'; 
        return $this->getResponse()->setBody("<script type='text/javascript'>$body</script>");
    }
    
	/**
     * Delete shoping cart item action
     */
    public function ajaxdeleteAction()
    {    	
        $id = (int) $this->getRequest()->getParam('id');
        if ($id) {
            try {
                $this->_getCart()->removeItem($id)
                  ->save();
            } catch (Exception $e) {
                $this->_getSession()->addError($this->__('Cannot remove the item.'));
                Mage::logException($e);
            }
        }
        $ajaxExpire = $this->_expireAjax();
        $miniCartHtml = $this->_getMiniCartHtml();
        $body = 'AjaxCart.updateBlock($$("div.mini-cart"),'.Mage::helper('core')->jsonEncode($miniCartHtml).');';             
        $body .= 'if($$("div.cart")!=""){AjaxCart.ajaxUpdateBlock("'.Mage::getUrl('*/*/ajaxUpdateCartPage/', array('_secure'=>true)).'");';        
        if (!$ajaxExpire)
        {
        	$body .= 'if($$("div.crosssell")!=""){AjaxCart.ajaxUpdateBlock("'.Mage::getUrl('*/*/ajaxUpdateCrossell/', array('_secure'=>true)).'");}';
        	$body .='if(typeof(billing)!="undefined"){billing.update();}'; 
        }
        $body .= '}';        
        return $this->getResponse()->setBody("<script type='text/javascript'>$body</script>");
    }
    
    public function ajaxUpdateCrossellAction()
    {
    	$crossellHtml = $this->_getCrossellHtml();
    	$body = 'AjaxCart.updateBlock($$("div.crosssell"),'.Mage::helper('core')->jsonEncode($crossellHtml).');';
    	return $this->getResponse()->setBody("<script type='text/javascript'>$body</script>");
    }
    
    public function ajaxUpdateCartPageAction()
    {
    	$ajaxExpire = $this->_expireAjax();
        $updateBlock = $ajaxExpire ? 'div.main' : 'div.cart';
    	$cartHtml = $this->_getCartHtml();  
    	$body = 'AjaxCart.updateBlock($$("'. $updateBlock .'"),'.Mage::helper('core')->jsonEncode($cartHtml).');';
    	return $this->getResponse()->setBody("<script type='text/javascript'>$body</script>");
    }
    
	protected function _getCartHtml()
    {
    	$layout = $this->getLayout();
    	$update = $layout->getUpdate();
    	$update->resetHandles();
    	$update->load('ajaxcart_cart_index');     	
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();
        return $output;
    }
    
	protected function _getCrossellHtml()
    {
    	$layout = $this->getLayout();
    	$update = $layout->getUpdate();
    	$update->resetHandles();
    	$update->load('ajaxcart_cart_crosssell');     	
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();
        return $output;
    }
    
	protected function _expireAjax()
    {
        if (!$this->_getQuote()->hasItems()) 
        {
            return true;
        }
        return false;
    }    
}
